//
//  HMNavigationController.swift
//  Weibo05
//
//  Created by IvesMac on 2017/6/8.
//  Copyright © 2017年 IvesMac. All rights reserved.
//

import UIKit

/// 自定义导航控制器视图

class HMNavigationController: UINavigationController,UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置屏幕边缘手势代理
        self.interactivePopGestureRecognizer?.delegate = self
        
    }

    // 重写push方法确定导航控制器里面的子控制器的个数
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        if viewControllers.count > 0 {
            if viewControllers.count == 1 {
                // 获取第一级控制器 ,设置它的leftBarButtonItem
                let title = viewControllers.first?.title
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: title!, imageName: "navigationbar_back_withtext", target: self, action: #selector(backAction))
            } else {
                
                // 设置这些控制器的leftBarButtonItem为 "返回"
                viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", imageName: "navigationbar_back_withtext", target: self, action: #selector(backAction))
            }
            
            viewController.title = "第\(viewControllers.count + 1)级控制器"
            
            //  MARK: -- 消除push的时候右上角的阴影
            //  一般有两种做法
            // 1.设置window的背景颜色
            // 2.设置tabbar的背景图片
            viewController.hidesBottomBarWhenPushed = true
        }
        super.pushViewController(viewController, animated: true)
    }
    
    // 返回按钮的点击事件
    @objc private func backAction() {
        
        self.popViewController(animated: true)
    }
    
    //  MARK: -- 实现边缘手势的代理方法
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        
        // 如果是根视图控制器,不要开启边缘手势
        if viewControllers.count == 1 {
            return false
        }
        
        return true 
    }
    
    
}

   
